import * as path from 'path';
import { isObject } from './util/lang';
import { Swagger, Options } from './interface';

export function loader(loaders: any[], content: Partial<Swagger>): any {
  return new Promise(resolve => {

    if (!loaders.length) {
      resolve(content);
      return;
    }

    let loaderFunctions = [];

    /**
     *  [{
          "loader": "format-loader",
          "options": {
            "regexp": "\/api\/",
            "replacement": ""
          }
        }]
        或
        [
          "services-loader"
        ]
     */
    loaders.forEach(item => {
      let loaderName = '';
      let options: Partial<Options> = {};

      if (isObject(item)) {
        loaderName = item.loader;
        options = item.options;
      } else {
        loaderName = item;
      }

      const loader = require(path.join(__dirname, `./loader/${loaderName}`));
      const key = Object.keys(loader)[0];
      loaderFunctions.push(loader[key].bind(null, options));
    });

    function nextLoader(content: Partial<Swagger>) {

      if (!loaderFunctions.length) {
        resolve(content);
        return;
      }

      const result = loaderFunctions.pop()(content);
      nextLoader(result);
    }

    nextLoader(content);
  });
};
